package com.toe.common.utils;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.InputStream;
import java.util.Properties;

public class ConfigUtils {

    private Logger logger = LoggerFactory.getLogger(ConfigUtils.class);
    private ResourceLoader resourceLoader = new DefaultResourceLoader();
    private Properties props = null;

    public ConfigUtils(String path) {
        try {
            reload(path);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    private ConfigUtils() {
    }

    public void reload(String path) throws Exception {
        if (props == null) {
            props = new Properties();
        }
        //测试环境
        String location = path;

        InputStream is = null;
        try {
            Resource resource = resourceLoader.getResource(location);
            is = resource.getInputStream();
            props.load(is);
        } catch (Exception ex) {
            logger.error("Could not load properties from path:{" + location + "}, {" + ex.getMessage() + "} ");
        } finally {
            IOUtils.closeQuietly(is);
        }

    }

    public String getString(String name) {
        if (props == null) {
            return null;
        }
        try {
            if (props.getProperty(name) != null) {
                return props.getProperty(name).trim();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "";
    }
}

